<script setup lang="ts">
import { useVModel } from '@vueuse/core'
import VehiclesPicker, { type ModelValueType } from './VehiclesPicker.vue'
import LicensePlate from '@/components/LicensePlate/license-plate.vue'

import { useFormDisabled, useFormSize } from 'element-plus'
import Plus from "~icons/ep/plus";
import { useRenderIcon } from '@/components/ReIcon/src/hooks'
import { type CSSProperties } from 'vue'
import { computed, ref } from 'vue'
export interface UserSelectorProps {
  modelValue: ModelValueType
  placeholder?: string
  multiple?: boolean
  disabled?: boolean
  style?: CSSProperties
}

const $props = withDefaults(defineProps<UserSelectorProps>(), {
  multiple: false,
  disabled: false,
  placeholder: '请选择车辆'
})
const $emits = defineEmits<{
  (e: 'update:modelValue', modelValue: ModelValueType): void
  (e: 'onSelected', userInfo: object): void
}>()
const vehicle = ref();
const value = useVModel($props, 'modelValue', $emits)
const valueArr = computed<string[]>(() => {
  if (!value.value) return []
  return Array.isArray(value.value) ? value.value : [value.value]
})
const VehiclesPickerRef = ref<InstanceType<typeof VehiclesPicker>>()
const formDisabled = useFormDisabled()
const formSize = useFormSize()
const disabled = computed<boolean>(() => {
  return formDisabled.value || $props.disabled
})
const openVehiclesPicker = () => {
  VehiclesPickerRef.value?.open()
}
const handelConfirm = (e) => {
  $emits('onSelected', e);
  console.log('handelConfirm：', e);
  vehicle.value = e[0];
}
const onClose = (username: string) => {
  if (!value.value) return
  if ($props.multiple && Array.isArray(value.value)) {
    value.value.splice(value.value.indexOf(username), 1)
  } else {
    value.value = null
  }
}
</script>

<template>
  <div class="w-[350px]" v-if="vehicle">
    <LicensePlate :plateNumber="vehicle.licensePlate" size="small" />
  </div>
  <div class="" v-else>
    <VehiclesPicker ref="VehiclesPickerRef" :multiple="multiple" @onSelected="handelConfirm" v-model="value" />
    <div class="user-wrapper">
      <el-button class="user-but-item" :size="formSize" :disabled="disabled" :icon="useRenderIcon(Plus)"
        @click="openVehiclesPicker" circle />
      <el-text v-show="!value || value.length === 0" class="placeholder">
        {{ placeholder }}
      </el-text>
    </div>
  </div>
</template>

<style scoped lang="scss">
.el-tag {
  padding: 0 3px;
}

.user-wrapper {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  grid-gap: 7px;
  gap: 7px;

  .placeholder {
    color: var(--el-text-color-placeholder);
  }

  .user-but-item {
    border-style: dashed;

    &:hover {
      border-style: solid;
    }
  }
}
</style>
